let express = require('express');
let common = require('../../libs/common.js');
const db = require('../../libs/db.js');
module.exports = function(){
    let loginRouter = express.Router();
    loginRouter.get('/',function(req,res){
        res.render('login/login.ejs',{});
    })
    loginRouter.post('/',function(req,res){
        let username = req.body.username;
        let password = req.body.password;
        let md5pwd = common.md5(password);
        console.log(md5pwd);
        if(!username || !password){
            res.status(400).send('用户名密码不能为空').end();
        }else{
            let sql = `SELECT uid,username,password FROM blog_user WHERE username='${username}'`;
            db.query(sql).then((data)=>{

                if(data.length==0 || md5pwd != data[0].password){
                    res.send('用户名或密码错误').end();
                }else{
                    req.session['admin_id'] = data[0].uid;
                    req.session['username'] = data[0].username;
                    res.redirect('/admin');
                }
            })
        }
    })
    return loginRouter;
}
